﻿#ifndef TOOLS_INCLUDED
#define TOOLS_INCLUDED

uniform float4x4 texViewProj;

inline float4 lightning(float4 lightPosition, float4 lightColour, float4 worldPos, float4x4 worldIT, float3 normal) {
	float3 worldNorm = mul(worldIT, normal).xyz;
	float3 lightDir = normalize(
		lightPosition.xyz - (worldPos.xyz * lightPosition.w));
	return lightColour * max(dot(lightDir, worldNorm), 0.0);
}

uniform float inverseShadowmapSize;

inline float4 inShadow(float4 position, float4 shadowUV, sampler2D shadowMap, float inverseShadowMapSize, float fixedDepthBias, float gradientClamp, float gradientScaleBias, float shadowIntensity) {
	float result;
	//shadowUV = shadowUV / shadowUV.w;
	//深度值 0 1  z 轴是 负向 还是正向
	//远 1  近 0  windows 上
	//less 深度 比较近
	shadowUV = shadowUV / 2 + 0.5;
	//深度值
	float centerdepth = tex2D(shadowMap, shadowUV.xy).x;
	//附近点采样 1/1024.0
	float pixeloffset = inverseShadowmapSize;
	float4 depths = float4(
		tex2D(shadowMap, shadowUV.xy + float2(-pixeloffset, 0)).x,
		tex2D(shadowMap, shadowUV.xy + float2(+pixeloffset, 0)).x,
		tex2D(shadowMap, shadowUV.xy + float2(0, -pixeloffset)).x,
		tex2D(shadowMap, shadowUV.xy + float2(0, +pixeloffset)).x);

	//深度变化
	float2 differences = abs(depths.yw - depths.xz);
	//gradient 不能超过
	float gradient = min(gradientClamp, max(differences.x, differences.y));
	//没用？ 0
	float gradientFactor = gradient * gradientScaleBias;

	//0.0016 * 中心点深度
	// visibility function
	float depthAdjust = gradientFactor + (fixedDepthBias * centerdepth);

	//修正中心深度
	float finalCenterDepth = centerdepth + depthAdjust;

	//当前对象在 阴影摄像机里面的 物体深度 0 ~ 1范围
	//临近点 上下左右 深度 depths
	//最终深度 > shadowUV.z 遮挡物在 地面下面
	//考虑临近点的遮挡

	// shadowUV.z contains lightspace position of current object
	// use depths from prev, calculate diff
	depths += depthAdjust.xxxx;
	float final = (finalCenterDepth > shadowUV.z) ? 1.0f : 0.0f;
	final += (depths.x > shadowUV.z) ? 1.0f : 0.0f;
	final += (depths.y > shadowUV.z) ? 1.0f : 0.0f;
	final += (depths.z > shadowUV.z) ? 1.0f : 0.0f;
	final += (depths.w > shadowUV.z) ? 1.0f : 0.0f;

	final *= 0.2f;

	result = final;


	return result * shadowIntensity + (1 - shadowIntensity);
}
#endif